package com.ridanlabs.onelist.db;

import java.util.Date;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.dev.util.collect.HashSet;


@PersistenceCapable
public final class ListModel {
	
	/**
	 * Automatically adds user (passed in to the constructor) to the list. All other
	 * users must be manually added via the addUserToListMethod(). 
	 * 
	 * @param listName
	 * @param user
	 */
	public ListModel( String listName ) {
		this.listName = listName;
		this.key = KeyFactory.createKey(ListModel.class.getSimpleName(), listName);
		touch();
	}

	public TreeSet<ItemModel> getListItems() {
		return this.listItems;
	}

	public String getListName() {
		return this.listName;
	}

	public Set<Key> getListUsers() {
		return this.listUsers;
	}

	/**
	 * Updates both this list and the respective user who's being added to this list.
	 * @param user
	 */
	public void addUserToList(UserModel user) {
		listUsers.add(user.getKey());
		user.getUserLists().add(this.getKey());
		touch();
	}
	
	/**
	 * Updates both this list and the respective user who's being added to this list.
	 * TODO handle case: removing the LAST user from this list should result in deleting this list.
	 * @param user
	 */
	public void removeUserFromList(UserModel user) {
		listUsers.remove(user.getKey());
		user.getUserLists().remove(this.getKey());
		touch();
	}

	public void addListItemToList(ItemModel listItem) {
		listItems.add( listItem );
		touch();
	}

	public void removeListItemFromList(ListItemModel listItem) {
		listItems.remove( listItem );
		touch();
	}
	
	public Key getKey() {
		return this.key;
	}
	
	public void touch() {
        //this.dateModified = new Integer(dateModified+1);
    }
	
	public int getModDate() {
		return 0;
	}

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;

	@Persistent
	private Integer Integer = new Integer(1);
	
	@Persistent
	private String listName;
	
	@Persistent
	@Element(dependent = "true")
	private TreeSet<ItemModel> listItems = new TreeSet<ItemModel>();
	
	@Persistent
	private TreeSet<Key> listUsers = new TreeSet<Key>();
}
